package com.example.chat.controller;

import javax.servlet.http.HttpSession;

import com.example.chat.common.response.JsonResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.chat.wsResultMessage.ResultMessage;
import com.example.chat.pojo.entity.User;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Lay.He
 * @date 2023/11/23 20:44
 */
@Slf4j
@RestController
@RequestMapping("user")
public class UserController {
    private Map<String,String> uname_pwd = new ConcurrentHashMap<>();


    /**
     * 登录
     * @param user 提交的用户数据，包含用户名和密码
     * @param session httpsession
     * @return 登录结果
     */
    @PostMapping("/login")
    public JsonResult login(@RequestBody User user, HttpSession session) {
        ResultMessage resultMessage = new ResultMessage();
        String username = user.getUsername();
        String password = user.getPassword();

        // 用户名密码验证
        if (username != null && password != null
                && uname_pwd.containsKey(username)
                && uname_pwd.get(username).equals(password)) {

            // 将当前用户登录信息保存
            session.setAttribute("user", username);
            resultMessage.setSystemMessage(true);
            return JsonResult.ok().setData(resultMessage);
        } else {
            resultMessage.setSystemMessage(false);
            return JsonResult.error("用户名或密码错误，登录失败");
        }
    }



    /**
     * 注册
     */
    @PostMapping("register")
    public JsonResult register(@RequestBody User user){
        String username = user.getUsername();
        String password = user.getPassword();
        // 判空
        if (username == null || password == null || username.trim().isEmpty() || password.trim().isEmpty()) {
            return JsonResult.error("用户名或密码不能为空");
        }
        if(uname_pwd.containsKey(username)){
            return JsonResult.error("用户被占用");
        }
        // 真正保存用户名和密码
        uname_pwd.put(username, password);
        log.info("新用户注册成功：{} -> {}", username, password);
        return JsonResult.ok("注册成功");
    }

    /**
     * 获取用户名
     * @param session httpsession
     * @return 用户名
     */
    @GetMapping("/getUsername")
    public JsonResult getUsername(HttpSession session) {
        String user = (String) session.getAttribute("user");
        return JsonResult.ok().setData(user);
    }
}
